package top.lixunda.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.security.SecureRandom;
import java.util.Random;
import java.util.UUID;


/**
 * @author Xumda
 * @version time:2019/12/7 10:56
 */
@SuppressWarnings({"WeakerAccess", "unused", "UnnecessaryLocalVariable"})
@Slf4j
public class StringUtils {

    private static final Random RANDOM = new SecureRandom();

    private static final String POINT = ".";

    /**
     * 验证码默认长度
     */
    private static final int CODE_LENGTH = 6;

    public static String getAuthCode() {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < CODE_LENGTH; i++) {
            builder.append(RANDOM.nextInt(10));
        }
        return builder.toString();
    }

    @SuppressWarnings("unchecked")
    public <T> T stringToBasicType(String str, Class<T> clazz) {
        if (ObjectValidators.isEmpty(str)) {
            return null;
        }
        switch (clazz.getName()) {
            case "java.lang.Integer":
                return (T) Integer.valueOf(str);
            default:
                return null;
        }
    }

    public static String getFileType(String name) {
        if (ObjectValidators.isEmpty(name) || name.length() == 0) {
            return "";
        }
        return name.substring(name.lastIndexOf(POINT));
    }

    public static String randomFileName(MultipartFile file) {
        if (ObjectValidators.isEmpty(file)) {
            return "";
        }
        String name = file.getOriginalFilename();
        String type = getFileType(name);
        return randomFileName(type);
    }

    public static String randomFileName(String type) {
        return randomFileName(type, null);
    }

    public static String randomFileName(String type, Integer size) {
        String name = UUID.randomUUID().toString();
        if (size != null && size > 0) {
            name = name.substring(0, size);
        }
        if (type != null && type.length() > 0 && !type.startsWith(POINT)) {
            type = "." + type;
        }
        return name + (type != null && type.length() > 0 ? type : "");
    }

}

